﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Antlr.Runtime;
using SQLAnalyticLibrary.Factory;
using SQLAnalyticLibrary.Expressions;

namespace SQLAnalyticLibrary
{
    public class SQLAnalytic
    {
        AstParserRuleReturnScope<Expression, IToken> statements = null;
        public SQLAnalytic(string sql)
        {
            OQLLexer lex = new OQLLexer(new CaseInsensitiveStringStream(sql));
            CommonTokenStream tokens = new CommonTokenStream(lex);
            OQLParser parser = new OQLParser(tokens);
            parser.TreeAdaptor = new TreeFactory();

            statements = parser.Start();
            if (statements == null || statements.Tree == null)
            {
                return;
            }


            //for (int i = 0; i < statements.tree.ChildCount; i++)
            //{
            //    Expression ex = statements.tree;
            //    QueryStatement query = new QueryStatement(ex.GetChild(i).Token);
            //    statements.tree.VisitCompile(query);
            //    _list.Add(query);
            //}
        }

        /// <summary>
        /// 是否可编辑表
        /// </summary>
        public string[] GetTableNames
        {
            get
            {
                try
                {
                    if (statements.Tree.Type == OQLLexer.SelectStmt)
                    {
                        return statements.Tree._children[1].Where(o=>o is Table).Select(o => (o as Table).TableName+"|"+(o as Table).AliasName).ToArray();
                    }
                    return new string[] { };
                }
                catch { return new string[] { }; }
            }
        }

        public Dictionary<int, int> GetFolding()
        {
            Dictionary<int, int> dic = new Dictionary<int, int>();
            if (statements.Tree != null)
            {
                if (statements.Tree.Type == OQLLexer.SelectStmt || 
                    statements.Tree.Type == OQLLexer.UnionStmt ||
                    statements.Tree.Type == OQLLexer.MultiLineComment)
                {
                    dic.Add(statements.Tree.TokenStartIndex, statements.Tree.TokenStopIndex);
                }
                else
                {
                    for (int i = 0; i < statements.Tree.ChildCount; i++)
                    {
                        Expression exp = statements.Tree._children[i];
                        if (exp.Type == OQLLexer.SelectStmt || 
                            exp.Type == OQLLexer.UnionStmt ||
                            exp.Type == OQLLexer.MultiLineComment)
                        {
                            dic.Add(exp.TokenStartIndex, exp.TokenStopIndex);
                        }
                    }
                }
            }
            return dic;
        }
    }
}
